package com.yin.casdemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo {
    public static void main(String[] args) {
        //        AtomicInteger atomicInteger = new AtomicInteger(2020);
        // 注意如果泛型是一个包装类，注意对象的引用问题
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(20, 1);
        /*
            public final boolean compareAndSet(int expect, int update)
            期望、更新
            如果期望的值达到了，更新
         */


        // 对于平时写的sql来说：乐观锁！
        new Thread(() -> {
            int stamp = atomicInteger.getStamp();
            System.out.println("a1 => " + stamp);
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            atomicInteger.compareAndSet(20, 22, stamp, stamp + 1);
            System.out.println("a2=>" + atomicInteger.getStamp());
        }, "A").start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int stamp = atomicInteger.getStamp();
            System.out.println("b1 => " + atomicInteger.getStamp());
        }, "B").start();
    }


}
